﻿using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.Form;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.Form
{
    public class CreateFormHandler:IRequestHandler<CreateFormCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<FormModel> formRepo;
        private readonly IMapper mapper;
        /// <summary>
        /// 注入添加表单所需的仓储和映射组件
        /// </summary>
        /// <param name="formRepo"></param>
        /// <param name="mapper"></param>
        public CreateFormHandler(IBaseRepository<FormModel> formRepo,IMapper mapper)
        {
            this.formRepo = formRepo;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(CreateFormCommand request, CancellationToken cancellationToken)
        {
            var model = mapper.Map<FormModel>(request);
            model.Id = YitIdHelper.NextId();//给主键赋值 

            var count = formRepo.GetAll().Count() + 1;//不能过滤已删除,并且还要+1
            model.FormCode ="F"+count.ToString().PadLeft(5, '0');

            int r = await formRepo.CreateAsync(model);
            if (r > 0)
            {
                return new ApiResult<int>().Success("添加表单成功!", r);
            }
            else { 
                return new ApiResult<int>().Fail("添加表单失败!");

            }
        }
    }
}
